import { defineStore } from 'pinia';
import axios from '@/plugins/http';
import { showToast, showConfirmDialog  } from 'vant';
import router from '@/router';
const useCartStore = defineStore('cart', {
    state() {
        return {
            // 购物车列表
            cartList: []
        }
    },
    actions: {
        // 重置购物车列表
        cartListInit(payload) {
            this.cartList = payload;
        },
        // 更新全选复选框的状态
        updateAllChecked(payload) {
            // 更新每一个商品选中状态
            this.cartList.forEach(item => {
                item.status = payload;
            });
        },
        // 添加购物车
        async cartAddAction( payload) {
            const { uid } = JSON.parse(localStorage.getItem('userLoginInfo') || '{}');
            if (!uid) {
                const result = await showConfirmDialog({
                    title: '提示',
                    message: '您还没有登录, 确认登录?',
                    overlay:false
                }).catch(() => null);
                if (result) {
                    router.push({ name: "login", query: { url: router.currentRoute.fullPath } });
                }
                return false;
            }
            axios.post('/cartadd', { uid, ...payload }).then(res => {
                if (res.code === 200) {
                    showToast(res.msg);
                    this.getCartList();
                }
            });
        },
        // 更新所有商品的选中状态
        updateAllCheckedAction(payload) {
            const { uid } = JSON.parse(localStorage.getItem("userLoginInfo") || '{}');
            const status = payload ? 1 : 0;
            axios.post('/cartUpdateAllChecked', { uid, status }).then((res) => {
                if (res.code === 200) {
                    this.updateAllChecked(status);
                }
            });
        },
        // 请求购物车列表
        getCartList(callback) {
            const { uid } = JSON.parse(localStorage.getItem('userLoginInfo') || '{}');
            if (!uid) {
                return showConfirmDialog ({
                    title:"提示",
                    message: '您还没有登录,确认登录?',
                    overlay:false
                })
                    .then(() => {
                        // on confirm
                        router.push({ name: "login", query: { url: router.currentRoute.value.fullPath } });
                    })
                    .catch(() => {
                        // on cancel
                    });
            }
            axios.get('/cartlist', { params: { uid } }).then(res => {
                if (res.code === 200) {
                    this.cartList = res.list ? res.list : [];
                    setTimeout(() => {
                        callback && callback();
                    }, 300);
                }
            });
        },
        // 删除购物车商品
        cartDelAction(payload) {
            axios.post('/cartdelete', { id: payload }).then(res => {
                if (res.code === 200) {
                    // 根据id查找索引
                    const index = this.cartList.findIndex(item => item.id === payload);
                    this.cartList.splice(index, 1);
                }
            });
        }
    },
    getters: {
        // 计算购物车商品总数
        cartGoodsCount(state) {
            let count = 0;
            state.cartList.forEach(item => {
                if (item.status == 1) {
                    count += item.num;
                }
            });
            return count;
        },
        // 计算购物车总价
        cartPrice(state) {
            let price = 0;
            state.cartList.forEach(item => {
                if (item.status == 1) {
                    price += item.price * item.num;
                }
            });
            // 将计算单位改为分
            return parseFloat(price * 100);
        },
        // 计算全选复选框选中状态
        originAllChecked(state) {
            let checked = true;
            state.cartList.forEach(item => {
                if (item.status == 0) {
                    checked = false;
                }
            });
            return checked;
        }
    }
});

export default useCartStore;